/**
 * 
 */
package zhoujian.oj.leetcode;

import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;

import org.junit.Test;

/**
 * @author hyper
 * @email zjkermit@gmail.com
 * @date Dec 26, 2013
 * @version 1.0
 * @description Write a function to find the longest common prefix string
 *              amongst an array of strings.
 */
public class LongestCommonPrefix {

	public String solution1(String[] strs) {
		int len = strs.length;
		if (len == 0) {
			return "";
		}
		if (len == 1) {
			return strs[0];
		}

		StringBuilder sb = new StringBuilder(strs[0]);

		for (int i = 1; i < len; i++) {
			int j = 0;
			while (j < sb.length() && j < strs[i].length()
					&& sb.charAt(j) == strs[i].charAt(j)) {
				j++;
			}
			sb.delete(j, sb.length());
		}

		return sb.toString();
	}

	@Test
	public void testSolution1() {
		String[] strs = new String[]{"asdfghjk", "asdfg", "asd"};

		assertThat(solution1(strs), is("asd"));
	}
}
